<template>
  <div>
    <el-dialog
      v-model="open"
      width="65%"
      :before-close="cancle"
      :title="title"
    >
      <el-row :gutter="10" style="margin-bottom: 4px">
        <el-col :span="3">
          <el-button type="primary" @click="handleAddPackage">新增</el-button>
        </el-col>
        <el-col :span="3">
          <el-button :disabled="form.sysExpensesPayableList.length < 1" type="primary" @click="submit">保存</el-button>
        </el-col>
      </el-row>
      <el-form ref="formRef" :model="form">
        <el-table
          ref="detailTable"
          v-loading="loading"
          :data="form.sysExpensesPayableList"
          border
          height="500px"
          show-summary
          :summary-method="data => getSummaries(data)"
        >
          <el-table-column label="服务商" align="center" width="155">
            <template #default="{ row, $index }">
              <el-form-item :prop="`sysExpensesPayableList.${$index}.serviceChannelCode`">
                <el-select
                  v-model="row.serviceChannelCode"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="dict in dicts[DictDirection.服务商]"
                    :key="dict.providerServiceCode"
                    placeholder="请选择服务商类型"
                    :label="dict.serviceWholeName"
                    :value="dict.providerServiceCode"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column
            label="提单号"
            prop="ladingNo"
            align="center"
            width="120"
          >
            <template #default="{ row, $index }">
              <el-form-item :prop="`sysExpensesPayableList.${$index}.ladingNo`">
                <el-input v-model.trim="row.ladingNo" disabled></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="费用名称"
            prop="feeName"
            align="center"
            width="150"
          >
            <template #default="{ row, $index }">
              <el-form-item :prop="`sysExpensesPayableList.${$index}.feeName`" :rules="[{ required: true, message: '请输入费用名称', trigger: ['blur', 'change'] }]">
                <el-select v-model="row.feeName" filterable clearable>
                  <el-option
                    v-for="dict in dicts[DictDirection.费用名称]"
                    :key="dict.feeValue"
                    :label="dict.feeName"
                    :value="dict.feeValue"
                    :disabled="row.status ? row.status !== '待确认' : false"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="单价"
            prop="unitPrice"
            align="center"
            width="160px"
          >
            <template #default="{ row, $index }">
              <el-form-item :prop="`sysExpensesPayableList.${$index}.unitPrice`" :rules="[{ required: true, message: '请输入金额', trigger: ['blur', 'change'] }]">
                <el-input-number v-model="row.unitPrice" :disabled="row.status ? row.status !== '待确认' : false"></el-input-number>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="数量"
            prop="number"
            align="center"
            width="160px"
          >
            <template #default="{ row, $index }">
              <el-form-item :prop="`sysExpensesPayableList.${$index}.number`" :rules="[{ required: true, message: '请输入金额', trigger: ['blur', 'change'] }]">
                <el-input-number
                  v-model="row.number"
                  :min="0"
                  :disabled="row.status ? row.status !== '待确认' : false"
                ></el-input-number>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="金额"
            prop="amount"
            align="center"
            width="160px"
          >
            <template #default="{ row }">
              {{ getSum(row) }}
            </template>
          </el-table-column>
          <el-table-column
            label="币种"
            prop="currency"
            align="center"
            width="120"
          >
            <template #default="{ row }">
              <el-form-item>
                <!-- <el-input  v-model="row.currency"  ></el-input> -->
                <el-select v-model="row.currency" :disabled="row.status ? row.status !== '待确认' : false">
                  <el-option
                    v-for="item in currencyList"
                    :key="item.key"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="汇率"
            prop="exchangeRate"
            align="center"
            width="80px"
          >
            <template #default="{ row }">
              <el-form-item>
                <el-input v-model="row.exchangeRate" :disabled="row.status ? row.status !== '待确认' : false" onkeyup="value=value.replace(/[^\d{1,}\.\d{1,}|\d{1,}]/g,'')"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="备注"
            prop="remark"
            align="center"
            width="200"
          >
            <template #default="{ row }">
              <el-form-item>
                <el-input v-model="row.remark" show-overflow-tooltip type="textarea"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            fixed="right"
            align="center"
            width="100"
          >
            <template #default="{ row, $index }">
              <el-button
                type="primary"
                text
                :disabled="row.feeName === '单报总金额'"
                @click="handleDel(row, $index)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, getCurrentInstance, defineProps } from 'vue'
import { ElButton, ElMessageBox, ElMessage } from 'element-plus'
import useDicts, { DictDirection } from '@/store/modules/dicts'

import { 
  airAndSeaTransportationAdd as addPay, 
  deleteSysExpensesPayableByIds as delPay, 
  selectSysExpensesPayableList as getPayList,
} from '@/api/expressManager/flySea'
// 运输类型
const props = defineProps({
  transportType: {
    type: Number,
    required: true,
  },
})

const dicts = useDicts()
dicts.setDicts(DictDirection.费用名称)
dicts.setDicts(DictDirection.服务商)
const currencyList = ref([
  {
    value: '1',
    label: '人民币',
    key: 0,
  },
  {
    value: '2',
    label: '美元',
    key: 1,
  },
]) 
const formRef = ref(undefined),
  {
    appContext: {
      config: {
        globalProperties: { $validateForm },
      },
    },
  } = getCurrentInstance()
const open = ref(false)
const title = ref(undefined)
const loading = ref(false)
const form = ref({
  sysExpensesPayableList: [],
  orderId: '',
  caseNo: '',
  transportType: 0,
})
const ladingNos = ref(undefined)
const caseNos = ref(undefined)
const idss = ref(undefined)
// 添加
const handleAddPackage = () => {
  form.value.sysExpensesPayableList.push({ serviceChannelCode: '', ladingNo: ladingNos.value, feeName: '', unitPrice: 0, number: 0, amount: 0, currency: '1', exchangeRate: '1' })
}
const cancle = () => {
  open.value = false
  formRef.value.resetFields()
}
const submit = () => {
  form.value.orderId = idss.value
  form.value.caseNo = caseNos.value
  form.value.transportType = props.transportType
  const data = form.value
  $validateForm(formRef.value, () => {
    loading.value = true
    addPay(data).then(res => {
      if (res.code == 200) {
        ElMessage.success('添加成功')
        getList()
      } else {
        ElMessage.error(res.msg)
      }
    }).finally(() => {
      loading.value = false
    })
  })
}

const handleDel = (row: { [key: string]: any }, index) => {
  if (row.id == undefined) {
    form.value.sysExpensesPayableList.splice(index, 1)
  } else {
    ElMessageBox.confirm('此操作将永久删除该包裹信息, 是否继续?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      delPay(row.id).then(res => {
        if (res.code == 200) {
          form.value.sysExpensesPayableList.splice(index, 1)
          getList()
          ElMessage.success('删除成功')
        } else {
          ElMessage.error(res.msg)
        }
      })
    })
  }
}
const getSummaries = (param) => {
  const { columns } = param
  let RMB = 0
  let Dollar = 0
  form.value.sysExpensesPayableList
  .filter(ele => ele.currency === '1')
  .forEach(item => {
    RMB = item.amount + RMB
  })
  form.value.sysExpensesPayableList
  .filter(c => c.currency === '2')
  .forEach(r => {
    Dollar = r.amount + Dollar
  })
  const sums = []
  const text1 = ' 人民币总计：'
  const price1 = ` ${ RMB.toFixed(2) }`
  const text2 = '美元总计：'
  const price2 = `  ${ Dollar.toFixed(2) }`
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = (() => {
        const el = text1
        return el
      })()
    } else if (index === 1) {
      sums[index] = (() => {
        const el = price1
        return el
      })()
    } else if (index === 2) {
      sums[index] = (() => {
        const el = text2
        return el
      })()
    } else if (index === 3) {
      sums[index] = (() => {
        const el = price2
        return el
      })()
    } 
  })
  return sums
}
const getSum = (row: { [key: string]: any }) => {
  // row.amount = 0
  if (row.unitPrice == undefined || row.number == undefined) {
    // eslint-disable-next-line no-return-assign
    return (row.amount = 0)
  } 
  // eslint-disable-next-line no-return-assign
  return (row.amount = row.number * row.unitPrice)
}
const getList = () => {
  const ladingNo = ladingNos.value
  const caseNo = caseNos.value
  const transportType = props.transportType
  getPayList({ ladingNo, transportType, caseNo }).then(res => {
    form.value.sysExpensesPayableList = res.data
  })
}
defineExpose({
  getList,
  open,
  title,
  ladingNos,
  idss,
  caseNos,
})
</script>
